<template>
  <div id="printBarcodeSpec">
    <Breadcrumb content="条码打印" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="16">
          <vxe-form :data="newForm" class-name="padding-sm width-100-percentage" title-width="80px">

            <vxe-form-item title="扫码" :item-render="{}" field="ewmNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input v-model="data.ewmNo" ref="ewmNoInput" placeholder="二维码" class-name="width-100-percentage"
                  @keyup="EWMNoValueChangeEnter" clearable />
              </template>
            </vxe-form-item>

            <vxe-form-item title="病历号" field="patNo" class-name="width-100-percentage" :item-render="{}">
              <template #default="{ data }">
                <vxe-input ref="inputRef" v-model="data.patNo" placeholder="病历号" class-name="width-100-percentage"
                  :disabled="loading" clearable @keyup="EWMNoValueChangeEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="病历号前缀" :item-render="{}" field="beforePatNo" class-name="width-100-percentage no-edit">
              <template #default="{ data }">
                <vxe-input v-model="data.beforePatNo" placeholder="病历号前缀" class-name="width-100-percentage"
                  :disabled="loading" clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请号" :item-render="{}" field="reqNo" class-name="width-100-percentage no-edit">
              <template #default="{ data }">
                <vxe-input v-model="data.reqNo" placeholder="申请号" class-name="width-100-percentage" :disabled="loading"
                  clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="床号" :item-render="{}" field="bedNo" class-name="width-100-percentage no-edit">
              <template #default="{ data }">
                <vxe-input v-model="data.bedNo" placeholder="床号" class-name="width-100-percentage" :disabled="loading"
                  clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <!--            <vxe-form-item title="病人来源" field="patTypeName" :item-render="{}" class-name="width-100-percentage">-->
            <!--              <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :displayField="[-->
            <!--                { title: '编码', props: 'code' }, //列标题-->
            <!--                { title: '名称', props: 'name' }-->
            <!--              ]" :title="'点击选择病人来源'" :searchParam="{ code: 'PATTYPE' }" @selectDataRow="SelectRowClick" :inputWidth="'100%'" v-model="newForm.patTypeName" :placeholder="'选择病人来源'" @clearValue="clearPatTypeName" @sliceValue="sliceHandler" />-->
            <!--              &lt;!&ndash; </template> &ndash;&gt;-->
            <!--            </vxe-form-item>-->

            <vxe-form-item title="病人来源" field="patTypeName" :item-render="{}" class-name="width-100-percentage no-edit">
              <SelectDataCheckedList ref="patTypeSelectRef" :url="'/api/sys/basDictDetail/findDictDetailList'" :column="[
                { field: 'code', title: '编码' }, //列标题
                { field: 'name', title: '名称' }
              ]" :searchParam="{ code: 'PATTYPE' }" :isPage="false" @SelectCellClick="(e) => {
  selectPatTypeNameRow(e, rowIndex);
}" :clickRowId="typeIds" :showField="'name'" :inputWidth="'100%'">
              </SelectDataCheckedList>
            </vxe-form-item>

            <vxe-form-item title="科室" :item-render="{}" field="deptNa" class-name="width-100-percentage">
              <SelectDataCheckedList ref="deptDropSelectRef" :url="'/api/sys/getDepartAuthorizementList'" :column="[
                { field: 'code', title: '科室编码' }, //列标题
                { field: 'name', title: '科室名称' }
              ]" :searchParam="{ orgId, username, deptNoList }" :isPage="false" @SelectCellClick="(e) => {
  selectDeptNaRow(e, rowIndex);
}
  " :clickRowId="deptIds" :showField="'name'" :inputWidth="'100%'">
              </SelectDataCheckedList>
            </vxe-form-item>

            <vxe-form-item title="姓名" :item-render="{}" field="patNa" class-name="width-100-percentage no-edit">
              <template #default="{ data }">
                <vxe-input v-model="data.patNa" placeholder="姓名" class-name="width-100-percentage" :disabled="loading"
                  clearable @keyup="keyupEnter" />
              </template>
            </vxe-form-item>

            <vxe-form-item title="身份证号" :item-render="{}" field="IDNo" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input ref="refInputIDNo" v-model="data.IDNo" placeholder="身份证号" class-name="width-100-percentage"
                  @keyup="IDNoValueChangeEnter" clearable />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请时间[始]" :item-render="{}" field="reqDateS" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input placeholder="申请时间[始]" v-model="data.reqDateS" type="datetime" class-name="width-100-percentage"
                  transfer />
              </template>
            </vxe-form-item>

            <vxe-form-item title="申请时间[止]" :item-render="{}" field="reqDateE" class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-input placeholder="申请时间[止]" v-model="data.reqDateE" type="datetime" class-name="width-100-percentage"
                  transfer />
              </template>
            </vxe-form-item>

            <vxe-form-item  class-name="width-100-percentage">
              <template #default="{ data }">
                <vxe-checkbox content="查看转科前未打印的检验申请单" v-model="data.filterotherDept" :checked-value="1"
                  :unchecked-value="0" @change="handleChange"></vxe-checkbox>
              </template>
            </vxe-form-item>

          </vxe-form>
        </Pane>
        <Pane size="84">
          <Splitpanes horizontal>
            <Pane size="50">
              <div>
                <vxe-toolbar perfect>
                  <template #buttons>
                    <!--                    <vxe-input v-model="newForm.searchValue" placeholder="请输入关键字" clearable @clear="findPrintBarcodeSpecList()" @keyup="keyupEnter"></vxe-input>-->
                    <vxe-button type="text" class="button-blue margin-left-sm" icon="vxe-icon-search"
                      class-name="text-blue" :disabled="loading" content="查询"
                      @click="findPrintBarcodeSpecList"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-paste" class-name="text-green"
                      class="button-blue margin-left-sm" content="读卡" @click="IdNoFocus"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-print" class-name="text-orange"
                      class="button-blue margin-left-sm" content="打印" :loading="isPrintting" :disabled="isPrintting"
                      @click="printManyStep1('printBarcodeSpecTable')"></vxe-button>
                    <!-- <vxe-button type="text" icon="vxe-icon-print" class-name="text-orange" content="测试插入申请项目" @click="testInsertAppItem"></vxe-button> -->
                    <!-- <vxe-button type="text" icon="vxe-icon-maximize" class-name="text-olive" content="重新打印" @click="findPrintBarcodeSpecList"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-delete-fill" class-name="text-red" content="删除" @click="findPrintBarcodeSpecList"></vxe-button> -->
                    <vxe-checkbox v-model="isPrintZYD" class="margin-left-xs" :checked-value="'1'"
                      :unchecked-value="'0'">打印回执单</vxe-checkbox>
                  </template>
                  <template #tools>
                    <span class="text-bold text-df margin-lr-xs vxe-icon-square-fill solid-bottom"
                      @dblclick="setCurComputerCheckedisPrintZYD">待打印条码申请</span>
                  </template>
                </vxe-toolbar>
              </div>
              <div class="printBarcodeSpecTable"
                :style="{ height: isChildren ? 'calc(100% - 40px - 40px)' : 'calc(100% - 40px)' }">
                <vxe-table ref="printBarcodeSpecTable" v-loading="loading" class="mytable-scrollbar" border height="auto"
                  align="left" :menu-config="tableMenuTop" @menu-click="contextMenuClickEvent" :cell-style="cellStyle"
                  :cell-class-name="cellClassName" @checkbox-change="checkboxStateChange"
                  @cell-click="printBarcodeSpecRowClick" :row-config="{ isCurrent: true, isHover: true }"
                  :keyboard-config="{ isArrow: true, isTab: true, isChecked: true }" resizable show-overflow
                  :scroll-y="{ enabled: true, gt: 50 }" show-footer :footer-method="footerMethodTop"
                  :data="printBarcodeList" :merge-footer-items="[{ row: 0, col: 1, rowspan: 1, colspan: 5 }]"
                  @checkbox-all="checkboxAll" :checkbox-config="checkboxConfig" :tooltip-config="tooltipConfig">
                  <vxe-column type="checkbox" width="26" fixed="left"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="catchMessage" title="异常提示" width="100">
                    <template #header>
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"></span>
                      <span class="margin-left-xs">异常提示</span>
                    </template>
                    <template #default="{ row }">
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"
                        v-if="!IsEmpty(row.catchMessage)"></span>
                      <span class="margin-left-xs" v-if="!IsEmpty(row.catchMessage)">{{ !IsEmpty(row.catchMessage) ?
                        row.catchMessage : '' }}</span>
                      <!--                      <span style="color: red" class="vxe-icon-warnion-circle-fill" v-if="row.isCatch"></span>-->
                      <!--                      <span class="margin-left-xs" v-if="row.isCatch">{{ row.isCatch ? row.catchMessage : '' }}</span>-->
                    </template>
                  </vxe-column>
                  <vxe-column field="isUrgent" title="急" width="26" align="center">
                    <template #default="{ row }">
                      <span>{{ row.isUrgent ? '是' : '' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column title="合" field="sameSpecCodeBgColor" width="26" align="center">
                    <template #header>
                      <span class="text-xs">合</span>
                    </template>
                    <template #default="{ row }">
                      <span class="margin-left-xs" v-if="row.isEnSameBg">&nbsp;</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="reqNo" title="条码号" sortable :sort-type="'string'" width="95px"></vxe-column>
                  <vxe-column field="patTypeNa" title="病人类型" width="75px"></vxe-column>
                  <vxe-column field="patNa" title="姓名" width="60px"></vxe-column>
                  <vxe-column field="sexNa" title="性别" width="30px"></vxe-column>
                  <vxe-column field="ageStr" title="年龄" width="50px"></vxe-column>
                  <vxe-column field="reqDeptNa" title="科室" width="80px"></vxe-column>
                  <vxe-column field="sampleTypeNa" title="样本类型" width="100"></vxe-column>
                  <vxe-column field="feeName" title="申请项目" width="280">
                    <template #default="{ row }">
                      <span>{{ `${row.feeCode} ${row.feeName}` }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="bedNo" title="床号" width="50px"></vxe-column>
                  <vxe-column field="reqTime" title="申请日期" min-width="120"></vxe-column>
                  <vxe-column field="applicantId" title="申请号" width="120"></vxe-column>
                  <vxe-column field="reqDoctorNa" title="开单医生" width="80"></vxe-column>
                  <vxe-column field="patNo" title="病历号" width="100"></vxe-column>
                  <vxe-column field="idNo" title="身份证号" width="100px"></vxe-column>
                  <vxe-column field="amount" title="数量" width="60" align="center"></vxe-column>
                  <vxe-column field="price" title="金额" width="60" align="right"></vxe-column>
                  <vxe-column field="adviceGroupId" title="医嘱分组Id" width="100"></vxe-column>
                  <vxe-column field="adviceId" title="医嘱Id" min-width="100"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
            <Pane size="50">
              <div>
                <vxe-toolbar perfect>
                  <template #buttons>
                    <vxe-input v-model="newForm.searchValue" placeholder="请输入关键字" clearable
                      @clear="newForm.searchValue = ''" @keyup="selectAllAfterPrintSpecs"></vxe-input>
                    <vxe-button type="text" icon="vxe-icon-print" class-name="text-green" content="重新打印"
                      class="button-blue margin-left-sm" @click="printAgain"></vxe-button>
                    <vxe-button type="text" icon="vxe-icon-delete" class-name="text-red"
                      class="button-blue margin-left-sm" content="清空已打印" @click="deleteAllAfterPrintSpecs"></vxe-button>
                  </template>
                  <template #tools>
                    <span class="text-bold text-df margin-lr-xs vxe-icon-square-fill solid-bottom">已打印条码</span>
                  </template>
                </vxe-toolbar>
              </div>
              <div class="printBarcodeSpecTable" :style="{
                height: isChildren ? 'calc(100% - 40px - 40px)' : 'calc(100% - 40px - 8px)'
              }">
                <vxe-table ref="afterPrintBarcodeSpecTable" v-loading="afterloading" class="mytable-scrollbar" border
                  height="auto" align="left" :menu-config="tableMenuBottom" @menu-click="contextMenuClickEvent1"
                  :cell-style="cellStyle" :cell-class-name="cellClassName" :data="selectAfterPrintBarcodeSpecList"
                  @checkbox-change="afterCheckboxStateChange" :row-config="{ isCurrent: true, isHover: true }"
                  :mouse-config="{ selected: true }" :keyboard-config="{ isArrow: true, isTab: true, isChecked: true }"
                   resizable show-overflow
                  :scroll-y="{ enabled: true, gt: 50 }" :checkbox-config="checkboxConfig" :tooltip-config="tooltipConfig">
                  <vxe-column type="checkbox" width="26" fixed="left"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="catchMessage" title="异常提示" width="100">
                    <template #header>
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"></span>
                      <span class="margin-left-xs">异常提示</span>
                    </template>
                    <template #default="{ row }">
                      <span style="color: red" class="vxe-icon-warnion-circle-fill"
                        v-if="!IsEmpty(row.catchMessage)"></span>
                      <span class="margin-left-xs" v-if="!IsEmpty(row.catchMessage)">{{ !IsEmpty(row.catchMessage) ?
                        row.catchMessage : '' }}</span>
                      <!--                      <span style="color: red" class="vxe-icon-warnion-circle-fill" v-if="row.isCatch"></span>-->
                      <!--                      <span class="margin-left-xs" v-if="row.isCatch">{{ row.isCatch ? row.catchMessage : '' }}</span>-->
                    </template>
                  </vxe-column>
                  <vxe-column field="isUrgent" title="急" width="26" align="center">
                    <template #default="{ row }">
                      <span>{{ row.isUrgent ? '是' : '' }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column title="合" field="sameSpecCodeBgColor" width="26" align="center">
                    <template #header>
                      <span class="text-xs">合</span>
                    </template>
                    <template #default="{ row }">
                      <span class="margin-left-xs" v-if="row.isEnSameBg">&nbsp;</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="reqNo" title="条码号" sortable :sort-type="'string'" width="95px"></vxe-column>
                  <vxe-column field="patTypeNa" title="病人类型" width="75px"></vxe-column>
                  <vxe-column field="patNa" title="姓名" width="60px"></vxe-column>
                  <vxe-column field="sexNa" title="性别" width="30px"></vxe-column>
                  <vxe-column field="ageStr" title="年龄" width="50px"></vxe-column>
                  <vxe-column field="reqDeptNa" title="科室" width="80px"></vxe-column>
                  <vxe-column field="sampleTypeNa" title="样本类型代码" width="100"></vxe-column>
                  <vxe-column field="feeName" title="申请项目" width="280">
                    <template #default="{ row }">
                      <span>{{ `${row.feeCode} ${row.feeName}` }}</span>
                    </template>
                  </vxe-column>
                  <vxe-column field="bedNo" title="床号" width="50px"></vxe-column>
                  <vxe-column field="reqTime" title="申请日期" min-width="120"></vxe-column>
                  <vxe-column field="applicantId" title="申请号" width="120"></vxe-column>
                  <vxe-column field="reqDoctorNa" title="开单医生" width="80"></vxe-column>
                  <vxe-column field="patNo" title="病历号" width="100"></vxe-column>
                  <vxe-column field="idNo" title="身份证号" width="100px"></vxe-column>
                  <vxe-column field="amount" title="数量" width="60" align="center"></vxe-column>
                  <vxe-column field="price" title="金额" width="60" align="right"></vxe-column>
                  <vxe-column field="adviceGroupId" title="医嘱分组Id" width="100"></vxe-column>
                  <vxe-column field="adviceId" title="医嘱Id" min-width="100"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
          </Splitpanes>
        </Pane>
      </Splitpanes>
    </div>
    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
    <!-- 静默打印-指引单 -->
    <QuietPrint ref="quietPrintZydRef" :printParams="printParamsZydObj" />
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import { reactive, ref, getCurrentInstance, onMounted, watch, inject } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { IsEmpty, IsReactiveEmpty, formatDateTime } from '@/utils/common';
import { VXETable, VxeFormPropTypes, VxeFormInstance, List } from 'vxe-table';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes'; //比例拖拉条
import SelectDataList from '@/components/SelectDataList.vue';
import { AppStore } from '@/stores/store';
import SelectDataCheckedList from '@/components/SelectMultDataGrid.vue';
import QuietPrint from '@/components/QuietPrint.vue';
import XEClipboard from 'xe-clipboard';
import { LocGet, LocPost } from '@/utils/LocRequestHelper';
import { initWebSocket, closeWebSocket } from '@/utils/websocketReadCard';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();
// 双击配置本机电脑默认病人来源1
let isPrintting = ref(false);
let showDefaultVisitTypeModal = false;
let isPrintZYD = ref('0'); //是否打印指引单
let isChildren = false;
let loading = ref(false);
let ewmNoInput = ref(null);
let afterloading = ref(false);
let afterPrintBarcodeSpecList: any = reactive([]); //已打印列表
let selectAfterPrintBarcodeSpecList: any = reactive([]); //已打印列表
let printBarcodeList: any = reactive([]); //待打印列表
let username = ref(''); /**对接His的操作人 */
let currentPrintBarcode = reactive({}) as any; //当前选中行
let currentRowIndex = ref(0);

let printParamsObj = ref(null); //打印参数
let printParamsZydObj = ref(null); /**指引单打印参数 */
let deptIds = ref('');
let typeIds = ref('');
let reportId = ref('');

let barCadeIds = ref('');

let orgId = ref(null);
const deptDropSelectRef = ref(null); /**科室下拉框 */
const patTypeSelectRef = ref(null); /**来源下拉框 */
const printBarcodeSpecTable = ref(null); //表格ref标记
const afterPrintBarcodeSpecTable = ref(null); /**已打印列表对象Ref */
let deptNoList = reactive([]);
const newForm = reactive({
  searchValue: '',
  patNo: '',
  beforePatNo: '',
  reqNo: '',
  bedNo: '',
  patType: [] as any,
  patTypeName: '',
  deptNo: [] as any,
  deptNa: '',
  patNa: '',
  IDNo: '',
  ewmNo: '',
  reqDateS: formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00'),
  reqDateE: formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59'),
  filterotherDept: 0
});

let isSearchLoading = ref(false);/* 查询是否加载中 */

let tableMenuTop = reactive({
  className: 'my-menus',
  body: {
    options: [[{ code: 'copy', name: '复制内容', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' }]]
  }
});
let tableMenuBottom = reactive({
  className: 'my-menus',
  body: {
    options: [[{ code: 'copy', name: '复制内容', prefixIcon: 'vxe-icon-copy', className: 'my-copy-item' }]]
  }
});

const checkboxConfig = reactive<VxeTablePropTypes.CheckboxConfig<RowVO>>({
  checkMethod: ({ row }) => {
    return IsEmpty(row.catchMessage);
  }
});
const formData= reactive({})
const tooltipConfig = reactive<VxeTablePropTypes.TooltipConfig>({
  showAll: true,
  enterable: true,
  contentMethod: ({ type, column, row, items, _columnIndex }) => {
    const { field } = column;
    // 重写默认的提示内容
    if (field === 'feeName') {
      return  formData[row.feeCode];
    }
  }
});
// 页面加载时更新报告单元/字典
onMounted(async () => {
  // setTimeout(() => {
  //   ewmNoInput.value.focus();
  // }, 200);
  orgId = store.userInfo.orgId;
  //#region  病人来源
  try {
    const url1 = (window as any).apiUrl.VUE_APP_LOCAL_PRINT_URL + `/api/LocalParams/get-local-setting?key=${'specPrintVisitType'}`;
    const r = await LocPost(url1);
    deptIds.value = r;
  } catch (err) { }
  //#endregion

  /* 本地参数 */
  try {
    const url1 = (window as any).apiUrl.VUE_APP_LOCAL_PRINT_URL + `/api/LocalParams/get-local-setting?key=${'BQMRCXTNDSQ'}`;/* 默认打印天数 */
    const r = await LocPost(url1);
    //newForm.reqDateS
    if (!IsEmpty(r)) {
      newForm.reqDateS = formatDateTime(new Date().valueOf() - Number(r) * 24 * 60 * 60 * 1000, 'yyyy-MM-dd 00:00:00');
    }
  } catch (err) { }

  try {
    const queryObj = proxy.$route.query;
    username.value = queryObj.username;
    if (username.value) {
      if (IsEmpty(queryObj.key)) {
        VxeMessage('参数key为空', VxeNotifyType.warning);
        return;
      } else {
        sessionStorage.setItem('QueryObjKey', queryObj.key);
      }
      //走免密登录逻辑
      let res = await login();
      if (!res) {
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('layoutSkin');
        localStorage.removeItem('moduleId');
        proxy.$router.push('/login');
        return;
      }
      finPermissionObj();
    }
    let isCondSearch = false;
    if (!IsEmpty(queryObj.patNo)) {
      newForm.patNo = queryObj.patNo;
      isCondSearch = true;
    }
    if (!IsEmpty(queryObj.beforePatNo)) {
      newForm.beforePatNo = queryObj.beforePatNo;
      isCondSearch = true;
    }
    if (!IsEmpty(queryObj.reqNo)) {
      newForm.reqNo = queryObj.reqNo;
      isCondSearch = true;
    }
    if (!IsEmpty(queryObj.bedNo)) {
      newForm.bedNo = queryObj.bedNo;
      isCondSearch = true;
    }
    if (!IsEmpty(queryObj.patTypeName)) {
      newForm.patTypeName = queryObj.patTypeName;
      isCondSearch = true;
    }
    if (!IsEmpty(queryObj.patType) && queryObj.patType.length > 0) {
      if (typeof queryObj.patType === 'string') {
        newForm.patType.length = 0;
        Object.assign(newForm.patType, [queryObj.patType]);
        typeIds.value = queryObj.patType;
        patTypeSelectRef.value?.findDataList();
      }
      if (typeof queryObj.patType === 'object') {
        newForm.patType.length = 0;
        Object.assign(newForm.patType, queryObj.patType);
        typeIds.value = queryObj.patType.join(',');
        patTypeSelectRef.value?.findDataList();
      }
      isCondSearch = true;
      sessionStorage.setItem('QueryPatType', typeIds.value);
    }
    if (!IsEmpty(queryObj.deptNo) && queryObj.deptNo.length > 0) {
      if (typeof queryObj.deptNo === 'string') {
        newForm.deptNo.length = 0;
        Object.assign(newForm.deptNo, [queryObj.deptNo]);
        deptNoList.length = 0;
        Object.assign(deptNoList, [queryObj.deptNo]);
        deptIds.value = queryObj.deptNo;
        deptDropSelectRef.value?.findDataList();
      }
      if (typeof queryObj.deptNo === 'object') {
        newForm.deptNo.length = 0;
        Object.assign(newForm.deptNo, queryObj.deptNo);
        deptNoList.length = 0;
        Object.assign(deptNoList, queryObj.deptNo);
        deptIds.value = queryObj.deptNo.join(',');
        deptDropSelectRef.value?.findDataList();
      }
      isCondSearch = true;
      sessionStorage.setItem('BarCodePrtDeps', deptIds.value);
    }
    if (!IsEmpty(queryObj.deptNa)) {
      if (!IsEmpty(queryObj.deptNa)) {
        newForm.deptNa = queryObj.deptNa.join(',');
        isCondSearch = true;
      }
    }
    if (!IsEmpty(queryObj.patNa)) {
      newForm.patNa = queryObj.patNa;
      isCondSearch = true;
    }
    if (!IsEmpty(queryObj.IDNo)) {
      newForm.IDNo = queryObj.IDNo;
      isCondSearch = true;
    }
    if (isCondSearch) {
      findPrintBarcodeSpecList();
    }
    if (IsEmpty(queryObj) || IsEmpty(queryObj.deptNo)) {
      let BarCodePrtDeps = sessionStorage.getItem('BarCodePrtDeps');
      if (!IsEmpty(BarCodePrtDeps)) {
        deptIds.value = BarCodePrtDeps;
        loadCacheDeps(BarCodePrtDeps);

        /**填充组织机构 */
        if (BarCodePrtDeps.indexOf(',') > -1) {
          const ass = BarCodePrtDeps.split(',');
          newForm.deptNo.length = 0;
          Object.assign(newForm.deptNo, ass);
        } else {
          Object.assign(newForm.deptNo, [BarCodePrtDeps]);
        }
      }
    }

    if (IsEmpty(queryObj) || IsEmpty(queryObj.patType)) {
      let queryPatType = sessionStorage.getItem('QueryPatType');
      if (!IsEmpty(queryPatType)) {
        typeIds.value = queryPatType;
        loadCachePatType(queryPatType);

        /**填充来源 */
        if (queryPatType.indexOf(',') > -1) {
          const ass = queryPatType.split(',');
          newForm.patType.length = 0;
          Object.assign(newForm.patType, ass);
        } else {
          Object.assign(newForm.patType, [queryPatType]);
        }
      }
    }

    //#region  显示病人来源
    if (IsEmpty(newForm.patTypeName) && !IsEmpty(newForm.patType)) {
      switch (newForm.patType) {
        case '1':
          newForm.patTypeName = '门诊';
          break;
        case '2':
          newForm.patTypeName = '急诊';
          break;
        case '3':
          newForm.patTypeName = '住院';
          break;
        case '4':
          newForm.patTypeName = '体检';
          break;
        default:
          break;
      }
    }
    //#endregion
  } catch (error) {
    console.log('获取对接参数出现错误', error);
  }
  getReportId();

  //#region  打印回执单设置
  try {
    const flag = localStorage.getItem('isPrintZYD');
    if (flag) {
      isPrintZYD.value = flag;
    }
  } catch (error) {
    //todo
  }
  //#endregion
  getAuthorizeDeptList();
});

let authorizeDeptList: any = reactive([]);
// 获取设计模式表单的选择表达式
function getAuthorizeDeptList() {
  authorizeDeptList.length = 0; //放入数据前清空数据
  const url = '/api/sys/getDepartAuthorizementList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { orgId, username: username.value, deptNoList } })
    .then((res: any) => {
      authorizeDeptList.push(...res.data);
    })
    .catch((err: any) => { });
}

/**加载缓存中的科室 */
function loadCacheDeps(depNos) {
  if (!deptDropSelectRef.value) {
    setTimeout(() => {
      loadCacheDeps(depNos);
    }, 200);
    return;
  }
  let arr = [];
  if (!IsEmpty(depNos) && depNos.includes(',')) {
    arr = depNos.split(',');
  } else {
    arr.push(depNos);
  }
  const url = '/api/sys/fingDepartmentNamesByCodes';
  proxy.$http.get(url, { params: { nos: arr } }).then((res: any) => {
    if (res && res.status && res.status.code && res.status.code === 1) {
      deptDropSelectRef.value?.initBaseText(!IsEmpty(res.data) ? res.data : '');
    }
  });
}

/**加载缓存中的来源 */
function loadCachePatType(patTypes) {
  if (!deptDropSelectRef.value) {
    setTimeout(() => {
      loadCachePatType(patTypes);
    }, 200);
    return;
  }
  let arr = [];
  if (!IsEmpty(patTypes) && patTypes.includes(',')) {
    arr = patTypes.split(',');
  } else {
    arr.push(patTypes);
  }
  //fixme:20241216这里需要修复
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http.get(url, { params: { code: 'PATTYPE' } }).then((res: any) => {
    if (res && res.status && res.status.code && res.status.code === 1) {
      //判断code是否在数组arr中存在
      const names = res.data.filter((item: any) => arr.includes(item.code));
      deptDropSelectRef.value?.initBaseText(!IsEmpty(names) ? names.map((item: any) => item.name).join(',') : '');
    }
  });
}

//根据字典ID查询报表
function getReportId() {
  const url = '/api/pubReport/getReportByReportCode';
  proxy.$http
    .get(url, { params: { reportCode: '1754032534504218624' } })
    .then((res: any) => {
      reportId = res.data;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// #endregion
function setCurComputerCheckedisPrintZYD() {
  const flag = localStorage.getItem('isPrintZYD');
  if (flag) {
    localStorage.removeItem('isPrintZYD');
    isPrintZYD.value = '0';
    VXETable.modal.message({ content: '取消配置成功', status: 'warning' });
  } else {
    localStorage.setItem('isPrintZYD', '1');
    isPrintZYD.value = '1';
    VXETable.modal.message({ content: '配置成功', status: 'success' });
  }
}

//单元格样式
function cellStyle({ row, rowIndex, column, columnIndex }) {
  if (column.property === 'sameSpecCodeBgColor') {
    return { backgroundColor: row.sameSpecCodeBgColor };
  }
}

//单元格背景颜色
function cellClassName({ row, rowIndex, column, columnIndex }) {
  if (column.property === 'isUrgent' && row.isUrgent) {
    return 'bg-red';
  }
}

function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    isSearchLoading.value = true;
    findPrintBarcodeSpecList();
  }
}

//扫码
function EWMNoValueChangeEnter(e: any) {
  if (e.$event.code == 'Enter') {
    const url = '/lab/hisReq/getIdCardByBarcode';
    proxy.$http
      .get(url, { params: { barcode: e.value } })
      .then((res: any) => {
        // ewmNoInput.value.focus()
        if (res.data) {
          newForm.ewmNo = res.data;
          newForm.patNo = res.data;
          findPrintBarcodeSpecList();
        }
      })
      .catch((err: any) => {
        VxeMessage('读取身份证号码失败', VxeNotifyType.error);
      });
  }
}

//身份证回车事件
function IDNoValueChangeEnter(e: any) {
  if (e.$event.code == 'Enter') {
    const url = '/lab/hisReq/getIdCardByBarcode';
    proxy.$http
      .get(url, { params: { barcode: e.value } })
      .then((res: any) => {
        // ewmNoInput.value.focus()
        if (res.data) {
          newForm.IDNo = res.data;
          newForm.ewmNo = '';
          findPrintBarcodeSpecList();
        }
      })
      .catch((err: any) => {
        VxeMessage('读取身份证号码失败', VxeNotifyType.error);
      });
  }
}

//读卡按钮
function IdNoFocus() {
  initWebSocket((item) => {
    const hasName = 'sbkh' in item.data;

    if (hasName) {
      //卡号 = item.data.sbkh

      //处理卡号

      //findPrintBarcodeSpecList();
      return;
    }

    if (item.code == 0) {
      newForm.IDNo = item.data.sfzh;
      findPrintBarcodeSpecList();
    } else {
      VxeMessage(item.msg, VxeNotifyType.error);
    }

    closeWebSocket();
  });
}

// 查询申请列表
function findPrintBarcodeSpecList() {
  if(newForm.filterotherDept == 1){
    if (IsEmpty(newForm.patNo)){
      VXETable.modal.confirm({ content: '请输入病历号查看所有未打印的检验申请单', status: 'error' });
      return;
    }
  }


  //判断病历号和身份证号同时为空时，不查询并进行提示
  // if (IsEmpty(newForm.IDNo) && IsEmpty(newForm.patNo)) {
  //   VxeMessage('请输入病历号或身份证号', VxeNotifyType.error);
  //   return;
  // }
  loading.value = true;
  printBarcodeList.length = 0;
  const url = '/lab/hisReq/barcodePrintSearch';
  const data = {
    patNo: newForm.patNo,
    beforePatNo: newForm.beforePatNo,
    reqNo: newForm.reqNo,
    bedNo: newForm.bedNo,
    patType: newForm.patType,
    deptNo: newForm.deptNo,
    patNa: newForm.patNa,
    IDNo: newForm.IDNo,
    ewmNo: newForm.ewmNo,
    reqDateS: newForm.reqDateS,
    reqDateE: newForm.reqDateE,
    searchValue: newForm.searchValue,
    filterotherDept: newForm.filterotherDept
  };
  if (data.deptNo.length == 0) {
    if (authorizeDeptList.length > 0) {
      let codes = authorizeDeptList.map((item: any) => item.code);
      data.deptNo = codes;
    } else {
      data.deptNo = ['!@#QWE'];
    }
  }
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      printBarcodeList.push(...res.data);
      if (printBarcodeList.length>0){
        let codeList = printBarcodeList.map((m: any) => m.feeCode);
        const feeCodeList  = codeList.join(',');
        findFeeCodeExtenFieldsValueList(feeCodeList);
      }
      proxy.$nextTick(() => {
        const $xTable = proxy.$refs.printBarcodeSpecTable as any;
        if (printBarcodeList && printBarcodeList.length > 0) {
          const rows = printBarcodeList.map((e) => {
            return IsEmpty(e.catchMessage) ? e : null;
          });
          $xTable.setCheckboxRow(rows, true);
          $xTable.updateFooter(); // 在值发生改变时更新表尾合计(一开始获取页面信息时调用计算表尾方法)
        }
      });
      selectAll();
      newForm.ewmNo = '';
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('查询列表失败', VxeNotifyType.error);
    });
}
function findFeeCodeExtenFieldsValueList(data: any) {
  console.log('data', data)
  Object.assign(newForm, {})
  const url = '/lis/fee/item/findFeeCodeExtenFieldsValueList';
  proxy.$http
      .get(url, {
        params: {
          moduleId: '1716657789982969857',
          menuId: '1734129954829893633',
          tabKey: '001',
          busRowId: data
        }
      })
      .then((res: any) => {
        if (res.data.length>0){
          res.data.forEach((item: any) => {
            formData[item.feeCode] = item.value;
          });
        }
        console.log('formData', formData)
      })
}
/**全部勾选 */
function checkboxAll() {
  printBarcodeSpecTable.value?.updateFooter();
}
//已打印列表勾选状态
function afterCheckboxStateChange({ checked, row, columns }) {
  const $xTable = proxy.$refs.afterPrintBarcodeSpecTable as any;
  const arr = afterPrintBarcodeSpecList.filter((e) => {
    return e.reqNo == row.reqNo;
  });
  if (arr && arr.length > 0) {
    arr.forEach((e) => {
      $xTable.setCheckboxRow(e, checked);
    });
    afterPrintBarcodeSpecTable.value?.updateFooter();
  }
}

//待打印勾选修改,为了勾选一个同医嘱的都勾选和取消
function checkboxStateChange({ checked, row }) {
  const $xTable = proxy.$refs.printBarcodeSpecTable as any;
  const arr = printBarcodeList.filter((e) => {
    return e.reqNo == row.reqNo;
  });
  if (arr && arr.length > 0) {
    arr.forEach((e) => {
      $xTable.setCheckboxRow(e, checked);
    });
  }
  printBarcodeSpecTable.value?.updateFooter();
  proxy.$forceUpdate();
}

//待打印行点击
function printBarcodeSpecRowClick({ row, rowIndex }) {
  if (IsEmpty(row)) {
    currentPrintBarcode = {} as any;
    return;
  }
  currentRowIndex = rowIndex;
  currentPrintBarcode = row;
  const xTable = proxy.$refs.printBarcodeSpecTable as any;
  xTable.setCurrentRow(row);
}

//打印按钮 (准备选中的数据)
function printManyStep1(tableName: any, isAgain = false) {
  isPrintting.value = true;
  const $xTable = proxy.$refs[tableName] as any;
  const selectRows = $xTable.getCheckboxRecords();

  if (!(selectRows && selectRows.length > 0 && selectRows[0])) {
    VxeMessage('请先选中要打印的条码', VxeNotifyType.info);
    isPrintting.value = false;
  } else {
    if (isAgain) {
      printManyStep3(selectRows, isAgain);
      return;
    }
    printManyStep2(selectRows);
  }
}

// 打印
function printManyStep2(arr) {
  const data = { labHisReqList: arr };
  const url = '/lab/hisReq/barcodePrint';
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      barCadeIds = res.data;
      printManyStep3(arr);
    })
    .catch((err: any) => {
      isPrintting.value = false;
      VxeMessage(err, VxeNotifyType.error);
    });
}

// 不是重打的打印之后数据放到重打列表
function printManyStep3(arr, isAgain = false) {
  console.log('arr', arr);
  
  selectAfterPrintBarcodeSpecList.length = 0;
  let arrIds = []; /**重打Id 集合 */
  if (!isAgain) {
    const $xTable = proxy.$refs.printBarcodeSpecTable as any;
    const indexArr = [];
    arr.forEach((element) => {
      const obj = Object.assign({}, element);
      const i = $xTable.getRowIndex(element);
      indexArr.push(i);
      afterPrintBarcodeSpecList.unshift(obj); //.unshift(obj);
    });
    selectAfterPrintBarcodeSpecList.unshift(...afterPrintBarcodeSpecList);
    console.log('selectAfterPrintBarcodeSpecList', selectAfterPrintBarcodeSpecList);
    
    $xTable.removeCheckboxRow();
  } else {
    //重打条码
    arr.forEach((item) => {
      arrIds.push(item.reqNo);
    });
  }
  let printAgainIds = arrIds ? arrIds.join(',') : '';
  // 调用报表,发送打印任务
  printParamsObj.value = [{ ReportName: reportId, ReportParameters: [{ Name: 'Id', Value: isAgain ? printAgainIds : barCadeIds }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }]; // { id: new Date().valueOf(), params: ['123', '345', '567'] };

  //打印导引单
  if (isPrintZYD.value && isPrintZYD.value === '1') {
    printParamsZydObj.value = [{ ReportName: '1768211380161925122', ReportParameters: [], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
  }

  // 清空查询条件
  clearFormConditions();
  isPrintting.value = false;
}

function clearFormConditions() {
  newForm.searchValue = '';
  newForm.patNo = '';
  newForm.beforePatNo = '';
  newForm.reqNo = '';
  newForm.bedNo = '';
  newForm.patType = [];
  newForm.deptNo = [];
  newForm.patNa = '';
  newForm.ewmNo = '';
  newForm.reqDateS = formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00');
  newForm.reqDateE = formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59');
}
//重打条码
function printAgain() {
  printManyStep1('afterPrintBarcodeSpecTable', true);
}

// 已打印搜索
function selectAllAfterPrintSpecs(value) {
  if (value.$event.key !== 'Enter') {
    return;
  }
  if (IsEmpty(newForm.searchValue)) {
    selectAfterPrintBarcodeSpecList.length = 0;
    selectAfterPrintBarcodeSpecList.push(...afterPrintBarcodeSpecList);
  }
  let arr = [];
  selectAfterPrintBarcodeSpecList.length = 0;
  //遍历afterPrintBarcodeSpecList，将搜索条件包含的数据push到selectAfterPrintBarcodeSpecList中
  for (const e of afterPrintBarcodeSpecList) {
    if (!IsEmpty(e.patNa) && e.patNa.indexOf(newForm.searchValue) > -1) {
      arr.push(e);
      continue;
    }
    if (!IsEmpty(e.patNo) && e.patNo.indexOf(newForm.searchValue) > -1) {
      arr.push(e);
      continue;
    }
    if (!IsEmpty(e.idNo) && e.idNo.indexOf(newForm.searchValue) > -1) {
      arr.push(e);
      continue;
    }
    if (!IsEmpty(e.reqNo) && e.reqNo.includes(newForm.searchValue)) {
      arr.push(e);
      continue;
    }
  }
  if (arr.length > 0) {
    selectAfterPrintBarcodeSpecList.push(...arr);
  }
}
// 清空已打印
function deleteAllAfterPrintSpecs() {
  afterPrintBarcodeSpecList.length = 0;
  selectAfterPrintBarcodeSpecList.length = 0;
}
//待打印条码 合并行
let totalJe = 0;
function footerMethodTop({ columns, data }) {
  const footerData = [
    columns.map((column, _columnIndex = 12) => {
      if (_columnIndex === 12) {
        const $xTable = proxy.$refs.printBarcodeSpecTable as any;
        const arr = $xTable.getCheckboxRecords();
        const sz = arr.map((p) => {
          return p.price;
        });
        totalJe = 0;
        const newsz = arr.reduce((prev, next) => {
          return prev + next.amount * next.price;
        }, 0);

        totalJe = newsz;
        return `金额合计: ${formatJe(totalJe)}  选中共计: ${arr.length} 项`;
      }
      return null;
    })
  ];

  return footerData;
}

function formatJe(v) {
  if (Number.isNaN(v)) {
    return '';
  }
  return Number(v).toFixed(2);
}

// 组件
//点击选择的那一项受检单位
function SelectRowClick(row) {
  newForm.patTypeName = row.name;
  newForm.patType = row.code;
}

// 清空表单值方法  子组件传递
function clearPatTypeName() {
  newForm.patTypeName = '';
  newForm.patType = [];
}

// 键盘事件删除输入框文字
function sliceHandler() {
  let newStr = newForm.patTypeName.slice(0, -1);
  newForm.patTypeName = newStr;
  let newStr1 = newForm.patType.slice(0, -1);
  newForm.patType = newStr1;
}

// 组件选中事件
function selectDeptNaRow(row, index) {
  deptIds.value = '';
  newForm.deptNo.length = 0;
  const nameArr = [];
  const deptIdArr = [];
  row.forEach((item) => {
    nameArr.push(item.name);
    newForm.deptNo.push(item.code);
    deptIdArr.push(item.code);
  });

  newForm.deptNa = nameArr.join(',');
  deptIds.value = deptIdArr.join(',');
}

// 病人来源组件选中事件
function selectPatTypeNameRow(row, index) {
  deptIds.value = '';
  newForm.patType.length = 0;
  const nameArr = [];
  const deptIdArr = [];
  row.forEach((item) => {
    nameArr.push(item.name);
    newForm.patType.push(item.code);
    deptIdArr.push(item.code);
  });

  newForm.patTypeName = nameArr.join(',');
  typeIds.value = deptIdArr.join(',');
}

/**待打印表格右键单机 */
function contextMenuClickEvent({ menu, row, column }) {
  switch (menu.code) {
    case 'copy':
      // 示例
      if (row && column) {
        if (XEClipboard.copy(row[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
      }
      break;
    default:
  }
}
/**已打印表格右键单机 */
function contextMenuClickEvent1({ menu, row, column }) {
  switch (menu.code) {
    case 'copy':
      // 示例
      if (row && column) {
        if (XEClipboard.copy(row[column.field])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
      }
      break;
    default:
    //VXETable.modal.alert(`点击了 ${menu.name} 选项`)
  }
}

/** 登录*/
function login() {
  return new Promise((resolve, reject) => {
    const url = '/public/user/loginByUserName';
    proxy.$http
      .post(url, {
        username: username.value,
        password: '',
        verifyCode: '',
        keyId: '1EB6FA91-4B29-4A5E-A448-1CDA1EC0FB03'
      })
      .then((res: any) => {
        if (res.status.code === 1) {
          store.setToken(res.data.token);
          const user: any = {
            id: res.data.user.id,
            hisEmployeeCode: res.data.user.hisEmployeeCode,
            realname: res.data.user.realname,
            tel: res.data.user.tel,
            username: res.data.user.username,
            orgId: res.data.user.orgId,
            orgName: res.data.user.organization ? res.data.user.organization.name : '',
            orgCode: res.data.user.organization ? res.data.user.organization.code : '',
            orgType: res.data.user.organization ? res.data.user.organization.type : '',
            layoutSkin: res.data.user.layoutSkin,
            systemList: res.data.user.SystemList,
            orgList: res.data.user.orgList
          };
          store.setUserInfo(user);
          resolve(true);
        }
      })
      .catch((err: string) => {
        resolve(false);
        VxeMessage(err, VxeNotifyType.warning);
      });
  });
}
function finPermissionObj() {
  proxy.$http
    .get('/api/user/sysUserAuthDetail/getLoginUserAuthMapByUserId', {
      params: {
        userId: store.userInfo.id
      }
    })
    .then((res: any) => {
      if (res.status.code !== 1) {
        VxeMessage(res.status.msg, VxeNotifyType.error);
        return;
      }
      localStorage.setItem('moduleId', '1747828187831173122');
      store.setRoleModel(res.data.modules);
      store.setModuleMenuMap(res.data.moduleMenuMap);
      store.setModulePointMap(res.data.modulePointCodeMap);
      store.setRptGroupList(res.data.rptGroupList);
      store.setInstrSetupList(res.data.instrSetupList);
    })
    .catch((err: string) => {
      VxeMessage('获取权限失败', VxeNotifyType.error);
    });
}

function selectAll() {
  proxy.$nextTick(() => {
    // proxy.$refs.inputRef.focus();
    proxy.$refs.inputRef.select();
  });
}


function handleChange(value){
  if(value.value == '1'){
    VXETable.modal.message({ content: '请输入病历号查看所有未打印的检验申请单', status: 'warning' });
    //VXETable.modal.confirm({ content: '111', status: 'warning' });
  }
}
</script>

<style lang="scss" scoped>
#printBarcodeSpec {
  height: 100%;
  width: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .area {
      background-color: $base-white;
    }
  }

  .printBarcodeSpecTable {
    height: calc(100vh - 160px);
  }
}

.custom-checkbox {
  font-size: 16px;
  cursor: pointer;
}

:deep(.vxe-body--row) {
  padding-left: 10px !important;
}

:deep(.no-edit-close) {
  user-select: none;
  /* 禁止选择文本 */
  pointer-events: none;
  /* 禁止所有鼠标事件 */
  cursor: none;

  .vxe-form--item-content {
    opacity: 0.6;
    //增加灰度
    filter: grayscale(100%);
  }
}</style>
